/**
 * FileName: TsfQueryExcutor
 * Author:   powersi
 * Date:     2021/1/12 8:46
 * Description:
 */
package com.zm.demo.httpclient;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Description: 
 * Author:      powersi
 * Date:        2021/1/12 8:46
 */
@Component
public class TsfQueryExcutor {

    CookieCache cookieCache = null;
    CookieCache tdsqlCookieCache = null;
    @Autowired
    MailService mailService;

    public static Map<String,String> mapParam = new HashMap<>();
    public static Map<String,String> tdsqlInstance = new HashMap<>();

    @PostConstruct
    public void scanTrace() throws Exception{
        mapParam.put("/fsi/api/fsiPsnInfoService/queryPsnInfo", "人员查询");
        mapParam.put("/fsi/api/fsiFixMedInsService/queryFixMedIns", "医药机构信息获取");
        mapParam.put("/fsi/api/fsiDrugStoreService/drugstoreSettleAccounts", "药店结算");
        mapParam.put("/fsi/api/outpatientDocInfoService/outpatientRregistration", "门诊挂号");
        mapParam.put("/fsi/api/outpatientDocInfoService/outpatientFeeListUp", "门诊费用明细信息上传");
        mapParam.put("/fsi/api/outpatientSettleService/saveSettletment", "门诊结算");
        mapParam.put("/fsi/api/hospFeeDtlService/feeDtlUp", "住院费用明细上传");
        mapParam.put("/fsi/api/hospSettService/sett", "住院结算");
        mapParam.put("/fsi/api/hospitalRegisterService/hospitalRegisterSave", "入院办理");
        mapParam.put("/fsi/api/dscgService/dischargeProcess", "出院办理");

        tdsqlInstance.put("/tdsqlzk/group_1597999212_278", "生产-异地就医业务库\n15065\n-group_1597999212_278");
        tdsqlInstance.put("/tdsqlzk/group_1600835079_1576", "生产-结算中心-待遇管理\n15067\ngroup_1600835079_1576");
        tdsqlInstance.put("/tdsqlzk/group_1600828525_1560", "生产-核心业务中台分布式数据库\n15215\ngroup_1600828525_1560");
        tdsqlInstance.put("/tdsqlzk/group_1600160522_1546", "生产-医保业务基础子系统分布式数据库\n15212\ngroup_1600160522_1546");
        tdsqlInstance.put("/tdsqlzk/group_1602554564_1630", "生产-病种分值数据库（分布式） 征缴中心\n15133\ngroup_1602554564_1630");


        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setName("定时扫描任务");
                return t;
            }
        });


        executorService.scheduleAtFixedRate(()->{
            Map<String,Map<String, Object>> map = new HashMap<>();
            Map<String,Map<String, Object>> tdsqlMap = new HashMap<>();
            Map<String,Map<String, Object>> tdsqlSlowSqlMap = new HashMap<>();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime localDateTime = LocalDateTime.now();
            String endTime = localDateTime.format(formatter);
            String startTime = localDateTime.plusMinutes(-10L).format(formatter);
            StringBuffer cookie = new StringBuffer();

            String tsfHost = System.getProperty("tsfHost","19.15.74.99");
            try {
                cookie.append(getCookie(tsfHost));
            } catch (Exception e){
                e.printStackTrace();
                return;
            }
            mapParam.entrySet().stream().forEach(e ->{
                try {
                    map.put(e.getKey(), HttpUtil.traces(tsfHost, startTime, endTime, e, "accessToken=" + cookie.toString()));
                } catch (Exception ex){
                    ex.printStackTrace();
                }
            });

            String tdsqlHost = System.getProperty("tdsqlHost","19.15.76.101");
            try {
                getTdsqlCookie(tdsqlHost);
            }catch (Exception e){
                e.printStackTrace();
            }
            tdsqlInstance.entrySet().stream().forEach(tdsql->{
                try {
                    tdsqlMap.put(tdsql.getKey(), HttpUtil.dbStatus(tdsqlHost, tdsql, tdsqlCookieCache.getCookie()));
                    tdsqlSlowSqlMap.put(tdsql.getKey(), HttpUtil.slowSql(tdsqlHost, startTime, endTime, tdsql, tdsqlCookieCache.getCookie()));
                } catch (Exception ex){
                    ex.printStackTrace();
                }
            });
            mailService.sendMsg(map, tdsqlMap, tdsqlSlowSqlMap, startTime, endTime);
        }, 0, 10, TimeUnit.MINUTES);

    }

    public String getCookie(String tsfHost) throws Exception{
        if (cookieCache == null || cookieCache.isExpire()){
            int retry = 3;
            while (retry-- > 0 && cookieCache == null){
                try {
                    cookieCache = HttpUtil.login(tsfHost);
                    break;
                } catch (Exception e) {
                    if (retry == 0){
                        throw e;
                    }
                }
            }
        }
        return cookieCache.getCookie();
    }

    public String getTdsqlCookie(String host) throws Exception{
        if (tdsqlCookieCache == null || tdsqlCookieCache.isExpire()){
            int retry = 3;
            while (retry-- > 0){
                try {
                    tdsqlCookieCache = HttpUtil.loginChitu(host);
                    break;
                } catch (Exception e) {
                    if (retry == 0){
                        throw e;
                    }
                }
            }
        }
        return tdsqlCookieCache.getCookie();
    }

}
